/**
 * Copyright 2008-2009 HAN.BIFANG
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package han.bashe.common.converter;

import java.util.Enumeration;

import javax.jms.TextMessage;

import org.apache.xmlbeans.XmlObject;

import han.bashe.common.exception.BasheErrorCode;
import han.bashe.common.exception.BasheException;
import han.bashe.common.message.MessageHeaderConstants;
import han.bashe.common.message.NormalizedMessage;

/**
 * @Author Kent 
 */
public class JmsConverter {
	
	public static NormalizedMessage toNormalized(TextMessage txt)throws Exception{
		NormalizedMessage msg = new NormalizedMessage();
		Enumeration<String> names = txt.getPropertyNames();
		while(names.hasMoreElements()){
			String name = names.nextElement();
			if(name.startsWith(MessageHeaderConstants.HEAD_PREFIX) ||
					name.startsWith(MessageHeaderConstants.HEAD_CUSTOM_PREFIX)){
				msg.setHead(name, txt.getStringProperty(name));
			}
		}
		try{
			XmlObject o = XmlObject.Factory.parse(txt.getText());
		}catch(Exception e){
			throw new BasheException(BasheErrorCode.PARSE_CLIENT_XML_ERROR,"HTTP Body is not a valid xml",e);
		}
		msg.setBody(txt.getText());
		return msg;
	}
	
	public static void setJmsMessage(NormalizedMessage msg, TextMessage txt)throws Exception{
		for(String name : msg.getHeads().keySet()){
			txt.setStringProperty(name, msg.getHead(name));
		}
		txt.setText(msg.getBody());
	}
}
